package com.beone.admin.interceptor;

import com.beone.admin.utils.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * App 登录拦截器
 * </p>
 *
 * @author Pagenny
 * @date 2019-05-19 12:27
 **/
@Component
public class AppLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenUtils tokenUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 请求的路径
        String contextPath = request.getContextPath();
        String token = tokenUtils.getTokenFromReq(request);
        if (StringUtils.isEmpty(token)) {
            request.getRequestDispatcher(contextPath + "/api/user/noToken").forward(request, response);
            return false;
        }
        String userId = tokenUtils.getUserId(token);
        if(StringUtils.isEmpty(userId)) {
            // 会话过期时的响应
            request.getRequestDispatcher(contextPath + "/api/user/noLogin").forward(request, response);
            return false;
        }
        request.setAttribute("userId", userId);
        // 重置token过期时间
        tokenUtils.setUserToken(userId, token);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
